package swingSection;

import java.util.ArrayList;
import java.util.List;

import javax.swing.table.AbstractTableModel;

import dataAccessLayer.DataGetter;
import entities.User;

public class MyTableModel extends AbstractTableModel{
	private String[] columnNames={"Username","User password"};
	private ArrayList<User> rows=new ArrayList<User>();
	@Override
	public int getColumnCount() {
		return columnNames.length;
	}

	@Override
	public int getRowCount() {
		return rows.size();
	}

	@Override
	public Object getValueAt(int row, int col) {
		if (row < 0 || row >= getRowCount() || 
				col < 0 || col >= getColumnCount()) {
				return null;
			}
			User user = rows.get(row);
			Object result = null;
			switch (col) {
			case 0:
				result = user.getUserName();
				break;
			case 1:
				result = user.getUserPassword();
				break;
			default:
				result = null;
			}
			
			return result;
		}
	public String getColumnName(int col){
		return columnNames[col];
	}
	
	public void setValueAt(Object value, int row, int col) {
		if (row < 0 || row >= getRowCount() || 
				col < 0 || col >= getColumnCount()) {
				return;
			}
			
			User user = rows.get(row);
			try {
				switch (col) {
				case 0:
					user.setUserName((String) value);
					break;
				case 1:
					break;
				default:
				}
				fireTableDataChanged();
			} catch (ClassCastException e) {
				e.printStackTrace();
			}
	}
	public void addUser(User user) {
		rows.add(user);
		fireTableDataChanged();
	}
	
	public void addUsers(List<User> users) {
		rows.addAll(users);
		fireTableDataChanged();
	}
	
	public void deleteUser(User user) {
		rows.remove(user);
		fireTableDataChanged();
	}
	
	public void editUser(User user) {
		int index = rows.indexOf(user);
		rows.set(index, user);
		fireTableDataChanged();
	}
	
	public void clear() {
		rows.clear();
		fireTableDataChanged();
	}
	
	@Override
	public int findColumn(String colName) {
		for (int colIndex = 0; colIndex < getColumnCount(); colIndex++) {
			if (colName.equalsIgnoreCase(columnNames[colIndex])) {
				return colIndex;
			}
		}
		return -1;
	}
}
